package com.rede.didiok.file.service.impl;

import java.util.*;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rede.didiok.common.constant.conf.MessageConf;
import com.rede.didiok.common.constant.conf.SQLConf;
import com.rede.didiok.common.constant.conf.SysConf;
import com.rede.didiok.common.constant.global.Constants;
import com.rede.didiok.common.dto.file.PictureDto;
import com.rede.didiok.common.enums.StatusEnum;
import com.rede.didiok.common.feign.RankFeignClient;
import com.rede.didiok.common.service.impl.SuperServiceImpl;
import com.rede.didiok.common.utils.ResultUtil;
import com.rede.didiok.common.utils.StringUtils;
import com.rede.didiok.common.utils.business.WebUtil;
import com.rede.didiok.file.dao.PictureDao;
import com.rede.didiok.file.entity.FileEntity;
import com.rede.didiok.file.entity.PictureCategoryEntity;
import com.rede.didiok.file.entity.PictureEntity;
import com.rede.didiok.file.service.FileService;
import com.rede.didiok.file.service.PictureCategoryService;
import com.rede.didiok.file.service.PictureService;

/**
 * 图片表 服务实现类
 *
 * @author 陌溪
 * @since 2018-09-04
 */
@Service("pictureService")
public class PictureServiceImpl extends SuperServiceImpl<PictureDao, PictureEntity> implements PictureService {

    @Autowired
    private WebUtil webUtil;

    @Autowired
    private PictureService pictureService;

    @Autowired
    private FileService fileService;

    @Autowired
    private RankFeignClient rankFeignClient;

    @Autowired
    private PictureCategoryService pictureCategoryService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /***************************** admin:start **************************/
    // region  didiok-admin

    /**
     * 通过fileIds获取图片信息
     *
     * @param fileIds
     * @param code
     * @return
     */
    @Override
    public String getPicture(String fileIds, String code) {
        List<Map<String, Object>> list = new ArrayList<>();
        if (StringUtils.isEmpty(code)) {
            code = Constants.SYMBOL_COMMA;
        }
        // 文件id为空，直接返回
        if (StringUtils.isEmpty(fileIds)) {
            return ResultUtil.successWithData(list);
        }

        List<String> changeStringToString = StringUtils.changeStringToString(fileIds, code);
        QueryWrapper<FileEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.in(SQLConf.UID, changeStringToString);
        List<FileEntity> fileList = fileService.list(queryWrapper);
        if (fileList.size() > 0) {
            for (FileEntity file : fileList) {
                if (file != null) {
                    Map<String, Object> remap = new HashMap<>();
                    // 获取七牛云地址
                    remap.put(SysConf.QI_NIU_URL, file.getQiNiuUrl());
                    // 获取Minio对象存储地址
                    remap.put(SysConf.MINIO_URL, file.getMinioUrl());
                    //获取阿里OSS对象存储地址
                    remap.put(SysConf.ALIOSS_URL, file.getAliOssUrl());
                    // 获取本地地址
                    remap.put(SysConf.URL, file.getPicUrl());
                    // 后缀名，也就是类型
                    remap.put(SysConf.EXPANDED_NAME, file.getPicExpandedName());
                    remap.put(SysConf.FILE_OLD_NAME, file.getFileOldName());
                    //名称
                    remap.put(SysConf.NAME, file.getPicName());
                    remap.put(SysConf.UID, file.getUid());
                    remap.put(SQLConf.FILE_OLD_NAME, file.getFileOldName());
                    list.add(remap);
                }
            }
        }
        return ResultUtil.result(SysConf.SUCCESS, list);
    }

    @Override
    public IPage<PictureEntity> getPageList(PictureDto pictureDto) {
        QueryWrapper<PictureEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(pictureDto.getKeyword()) && !StringUtils.isEmpty(pictureDto.getKeyword().trim())) {
            queryWrapper.like(SQLConf.PIC_NAME, pictureDto.getKeyword().trim());
        }

        Page<PictureEntity> page = new Page<>();
        page.setCurrent(pictureDto.getCurrentPage());
        page.setSize(pictureDto.getPageSize());
        queryWrapper.eq(SQLConf.STATUS, StatusEnum.ENABLE);
        queryWrapper.eq(SQLConf.PICTURE_CATEGORY_UID, pictureDto.getPictureCategoryUid());
        queryWrapper.orderByDesc(SQLConf.CREATE_TIME);
        IPage<PictureEntity> pageList = pictureService.page(page, queryWrapper);
        List<PictureEntity> pictureList = pageList.getRecords();

        final StringBuffer fileUids = new StringBuffer();
        pictureList.forEach(item -> {
            if (StringUtils.isNotEmpty(item.getFileUid())) {
                fileUids.append(item.getFileUid() + SysConf.FILE_SEGMENTATION);
            }
        });

        String pictureResult = null;
        Map<String, String> pictureMap = new HashMap<>();

        if (fileUids != null) {
            pictureResult = fileService.getPicture(fileUids.toString(), SysConf.FILE_SEGMENTATION);
        }
        List<Map<String, Object>> picList = webUtil.getPictureMap(pictureResult);

        picList.forEach(item -> {
            pictureMap.put(item.get(SysConf.UID).toString(), item.get(SysConf.URL).toString());
        });

        for (PictureEntity item : pictureList) {
            if (StringUtils.isNotEmpty(item.getFileUid())) {
                item.setPictureUrl(pictureMap.get(item.getFileUid()));
            }
        }
        pageList.setRecords(pictureList);
        return pageList;
    }

    @Override
    public String addPicture(List<PictureDto> pictureVOList) {
        List<PictureEntity> pictureList = new ArrayList<>();
        if (pictureVOList.size() > 0) {
            for (PictureDto pictureDto : pictureVOList) {
                PictureEntity picture = new PictureEntity();
                picture.setFileUid(pictureDto.getFileUid());
                picture.setPictureCategoryUid(pictureDto.getPictureCategoryUid());
                picture.setPicName(pictureDto.getPicName());
                picture.setStatus(StatusEnum.ENABLE);
                pictureList.add(picture);
            }
            pictureService.saveBatch(pictureList);
        } else {
            return ResultUtil.errorWithMessage(MessageConf.INSERT_FAIL);
        }
        return ResultUtil.successWithMessage(MessageConf.INSERT_SUCCESS);
    }

    @Override
    public String deleteBatchPicture(PictureDto pictureDto) {
        // 参数校验
        // 图片删除的时候，是携带多个id拼接而成的
        String uidStr = pictureDto.getUid();
        if (StringUtils.isEmpty(uidStr)) {
            return ResultUtil.errorWithMessage(MessageConf.PARAM_INCORRECT);
        }
        List<String> uids = StringUtils.changeStringToString(pictureDto.getUid(), SysConf.FILE_SEGMENTATION);
        for (String item : uids) {
            PictureEntity picture = pictureService.getById(item);
            picture.setStatus(StatusEnum.DISABLED);
            picture.setUpdateTime(new Date());
            picture.updateById();
        }
        return ResultUtil.successWithMessage(MessageConf.DELETE_SUCCESS);
    }

    @Override
    public String setPictureCover(PictureDto pictureDto) {
        PictureCategoryEntity pictureSort = pictureCategoryService.getById(pictureDto.getPictureCategoryUid());
        if (pictureSort != null) {
            PictureEntity picture = pictureService.getById(pictureDto.getUid());
            if (picture != null) {
                pictureSort.setFileUid(picture.getFileUid());
                picture.setUpdateTime(new Date());
                pictureSort.updateById();
            } else {
                return ResultUtil.errorWithMessage(MessageConf.THE_PICTURE_NOT_EXIST);
            }
        } else {
            return ResultUtil.errorWithMessage(MessageConf.THE_PICTURE_SORT_NOT_EXIST);
        }
        return ResultUtil.successWithMessage(MessageConf.UPDATE_SUCCESS);
    }

    @Override
    public PictureEntity getTopOne() {
        QueryWrapper<PictureEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SQLConf.STATUS, StatusEnum.ENABLE);
        queryWrapper.orderByAsc(SQLConf.CREATE_TIME);
        queryWrapper.last(SysConf.LIMIT_ONE);
        PictureEntity picture = this.getOne(queryWrapper);
        return picture;
    }
    // endregion
    /***************************** admin:end **************************/



    /***************************** web:start **************************/
    // region didiok-web

    // endregion
    /***************************** web:end **************************/


    /**
     * 插入图片
     *
     * @param pictureEntity
     */
    @Override
    public void savePicture(PictureEntity pictureEntity) {
        this.baseMapper.insert(pictureEntity);
    }


    /**
     * 根据uid更新图片
     *
     * @param pictureDto
     * @return
     */
    @Override
    public boolean updatePictureById(PictureDto pictureDto) {
        PictureEntity pictureEntity = new PictureEntity();
        BeanUtils.copyProperties(pictureDto, pictureEntity);
        return pictureEntity.updateById();
    }

}
